const gulp = require('gulp')
const {all, htmlList, cssList, jsList, imagesList, dist} = require('./build/gulp-config')
const html = require('./build/gulp-html-model')
const css = require('./build/gulp-css-model')
const js = require('./build/gulp-js-model')
const img = require('./build/gulp-image-model')
const copy = require('./build/gulp-copy-model')
const Path = require('path')
const rename = require('gulp-rename')
const fs = require('fs')

const env = process.env.NODE_ENV

function negation (arr) {
  return arr.map(v => `!${v}`)
}

let configPath = './config' + (env === 'dev'? '/dev-env.js' : env === 'test'?'/test-env.js' :'/prod-env.js')

gulp.task('config', () => {
  console.log(configPath)
  gulp.src(configPath)
    .pipe(rename('config/index.js'))
    .pipe(gulp.dest('./dist'))
})

const others = all.concat(['!src/assets/bgImages/**'], negation(cssList), negation(htmlList), negation(jsList), negation(imagesList))

gulp.task('html', html(htmlList))

gulp.task('css', css(cssList))

gulp.task('js', js(jsList))

gulp.task('images', img(imagesList.concat(['!src/assets/bgImages/**'])))

gulp.task('other', copy(others))

gulp.task('clear', () => {
  (function () {
    function iterator (url, dirs) {
      var stat = fs.statSync(url);
      if (stat.isDirectory()) {
        dirs.unshift(url);//收集目录
        inner(url, dirs);
      } else if (stat.isFile()) {
        fs.unlinkSync(url);//直接删除文件
      }
    }

    function inner (path, dirs) {
      var arr = fs.readdirSync(path);
      for (var i = 0, el; el = arr[i++];) {
        iterator(path + "/" + el, dirs);
      }
    }

    return function (dir, cb) {
      cb = cb || function () {
      };
      var dirs = [];

      try {
        iterator(dir, dirs);
        for (var i = 0, el; el = dirs[i++];) {
          fs.rmdirSync(el);//一次性删除所有收集到的目录
        }
        cb()
      } catch (e) {//如果文件或目录本来就不存在，fs.statSync会报错，不过我们还是当成没有异常发生
        e.code === "ENOENT" ? cb() : cb(e);
      }
    }
  })()(dist)
})

gulp.task('build', ['config', 'images', 'css', 'js', 'html', 'other'])

function changePath (path) {
  return Path.relative(__dirname, path).replace(/\\/g, '/')
}

function watchHandle (cb) {
  return e => {
    const newPath = changePath(e.path)
    if (e.type === 'deleted') {
      let distFile = './dist/' + Path.relative('./src', newPath);
      fs.existsSync(distFile) && fs.unlinkSync(distFile)
    } else {
      cb(newPath)()
    }
    console.log('File ' + e.path + ' was ' + e.type + ', running tasks...')
  }
}

gulp.task('dev', ['config', 'images', 'css', 'js', 'html', 'other'], () => {
    gulp.watch(imagesList, watchHandle(img))

    gulp.watch(jsList, watchHandle(js))

    gulp.watch(cssList, watchHandle(css))

    gulp.watch(htmlList, watchHandle(html))

    gulp.watch(others, watchHandle(copy))
  }
)
